import { useEffect, useState } from 'react';
import { Button, Table, Form, Input, DatePicker, Select, Checkbox, message } from 'antd';
import moment from 'moment';
import { uniqBy, every, uniq } from 'lodash';
import { activitySearchByCampaigncode, activitySearch } from '@/services/operate';

import RenderExpandedRow from './RenderExpandedRow/index';
import styles from './style.less';

interface Props {
  back: () => void;
  changeActivity: (data: any) => void;
  activityDataFather: any;
  step: number;
}

const ChooseActivty: React.FC<Props> = (props) => {
  const { back, changeActivity, activityDataFather, step } = props;
  const [queryForm] = Form.useForm(); // 筛选条件
  const channelWatch = Form.useWatch('channel', queryForm);
  const checkWatch = Form.useWatch('check', queryForm);

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [activityData, setActivityData] = useState<any>([]);
  const [tableData, setTableData] = useState([]);
  const [pageNo, setPageNo] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(1);
  const [expandId, setExpandId] = useState(-1);
  const [detailItem, setDetailItem] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [btnLoading, setBtnLoading] = useState(false);

  useEffect(() => {
    if (step && step === 2) {
      setActivityData(activityDataFather);
      setSelectedRowKeys(activityDataFather.map((item: any) => item.activityId));
    }
  }, [step]);

  const getList = async () => {
    const formValues = queryForm.getFieldsValue();
    setLoading(true);
    const { code, data } = await activitySearch({
      pageNo: pageNo,
      pageSize: pageSize,
      brandId: '002',
      activityId: formValues.activityId,
      activity: formValues.activity,
      activityStartTime:
        formValues.timeRange && formValues.timeRange[0]
          ? moment(formValues.timeRange[0]).format('YYYY-MM-DD')
          : '',
      activityEndTime:
        formValues.timeRange && formValues.timeRange[1]
          ? moment(formValues.timeRange[1]).format('YYYY-MM-DD')
          : '',
      onlyOpenPlace: formValues.check.length > 0,
      channel: formValues.channel,
      campaigncode: formValues.campaignCode,
    });
    setLoading(false);

    if (code === 200 && data) {
      setTableData(data.rows);
      setPageNo(data.pageNo);
      setPageSize(data.pageSize);
      setTotal(data.totalCount);
    }
  };

  useEffect(() => {
    if (pageNo === 1) {
      getList();
    } else {
      setPageNo(1);
    }
  }, [checkWatch]);

  useEffect(() => {
    getList();
  }, [pageNo, pageSize]);

  const columns = [
    {
      title: '活动定义',
      dataIndex: 'activityId',
      key: 'activityId',
      width: 180,
      ellipsis: true,
    },
    {
      title: 'Campaign Code',
      dataIndex: 'campaignCode',
      key: 'campaignCode',
      width: 200,
      ellipsis: true,
    },
    {
      title: '活动名称',
      dataIndex: 'activity',
      key: 'activity',
      width: 200,
      ellipsis: true,
    },
    {
      title: '活动有效期',
      dataIndex: 'activityStartTime',
      key: 'activityStartTime',
      width: 300,
      render: (text: any, record: any) => (
        <>
          {record.activityStartTime}-{record.activityEndTime}
        </>
      ),
    },
    {
      title: 'Rank Value（实际值）',
      dataIndex: 'actualRankValue',
      key: 'actualRankValue',
      width: 180,
      ellipsis: true,
      sorter: (a: any, b: any) => a.actualRankValue - b.actualRankValue,
      render: (text: any, record: any) => <>{record.actualRankValue || 0}</>,
    },
    {
      title: 'Rank Value（历史参考值）',
      dataIndex: 'expectRankValue',
      key: 'expectRankValue',
      width: 180,
      ellipsis: true,
      sorter: (a: any, b: any) => a.expectRankValue - b.expectRankValue,
      render: (text: any, record: any) => <>{record.expectRankValue || 0}</>,
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 120,
      align: 'center',
      render: (text: any, record: any) => (
        <div>
          <a
            onClick={() => {
              if (record.activityId === expandId) {
                setExpandId(-1);
                setDetailItem(null);
              } else {
                setDetailItem(record);
                setExpandId(record.activityId);
              }
            }}
          >
            活动效果
          </a>
        </div>
      ),
    },
  ];

  const onSelectChange = (record: any, selected: any, selectedRows: any) => {
    if (selected) {
      setSelectedRowKeys(selectedRowKeys.concat(record.activityId));
      setActivityData(activityData.concat(record));
    } else {
      const newSelectedRowKeys = selectedRowKeys.filter((item: any) => item !== record.activityId);
      setSelectedRowKeys(newSelectedRowKeys);
      const newActivityData = activityData.filter(
        (item: any) => item.activityId !== record.activityId,
      );
      setActivityData(newActivityData);
    }
  };

  const onSelectChangeAll = (status: any, _: any, selectedRows: any) => {
    const arr = selectedRows.map((item: any) => item.activityId) || [];
    if (status) {
      setSelectedRowKeys([...selectedRowKeys, ...arr]);
      setActivityData([...activityData, ...selectedRows]);
    } else {
      const newSelectedRowKeys = selectedRowKeys.filter((item: any) => !arr.includes(item));
      setSelectedRowKeys(newSelectedRowKeys);
      const newActivityData = activityData.filter((item: any) => !arr.includes(item.activityId));
      setActivityData(newActivityData);
    }
  };

  const rowSelection = {
    selectedRowKeys,
    // hideSelectAll: true,
    onSelect: onSelectChange,
    onSelectAll: onSelectChangeAll,
  };

  const onChangePagination = (pagination: any) => {
    setPageNo(pagination.current);
    setPageSize(pagination.pageSize);
  };

  // 查询--接口
  const handleQuey = () => {
    const values = queryForm.getFieldsValue();
    console.log('values', values);
    if (pageNo === 1) {
      getList();
    } else {
      setPageNo(1);
    }
  };

  const resetForm = () => {
    queryForm.resetFields();
  };

  const handleSure = async () => {
    // const uniqueCampaignCode = uniqBy(activityData, 'campaignCode');

    const allExist = every(activityData, (item: any) => item.campaignCode || item.campaigncode);
    if (activityData.length === 0) {
      message.error('请选择活动');
      return;
    }

    if (!allExist) {
      message.error('选择的活动中的Campaign Code不能为空');
      return;
    }

    const campaignCodeBro = activityData.map((item: any) => item.campaignCode.split('-')[0]);
    const uniqueCampaignCode = uniq(campaignCodeBro);

    console.log('campaignCodeBro', campaignCodeBro);
    console.log('uniqueCampaignCode', uniqueCampaignCode.length);
    console.log('allExist', allExist);
    console.log('activityData', activityData);

    if (uniqueCampaignCode.length === 1 && allExist) {
      const formValues = queryForm.getFieldsValue();
      const param = {
        // activityId: formValues.activityId,
        brandName: 'KFC',
        // onlyOpenPlace: formValues.check.length > 0,
        // channel: formValues.channel,
        // campaigncode: activityData[0].campaignCode,
        // activity: formValues.activity,
        // activityStartTime:
        //   formValues.timeRange && formValues.timeRange[0]
        //     ? moment(formValues.timeRange[0]).format('YYYY-MM-DD')
        //     : '',
        // activityEndTime:
        //   formValues.timeRange && formValues.timeRange[1]
        //     ? moment(formValues.timeRange[1]).format('YYYY-MM-DD')
        //     : '',
        activityIdList: activityData.map((item: any) => item.activityId), // 731版本再次调整
      };
      setBtnLoading(true);
      const { code, data } = await activitySearchByCampaigncode(param);
      setBtnLoading(false);
      if (code === 200 && data) {
        changeActivity(data);
        back();
      }
    } else {
      message.error('仅可选择同一个Campaign Code下的活动，请重新选择');
    }
  };

  return (
    <div className={styles['detail-activty']}>
      <Form
        labelCol={{ span: 11 }}
        form={queryForm}
        initialValues={{
          // SMK20240151295_10000
          activityId: '',
          activity: '',
          timeRange: [null, null],
          channel: 'CPOS',
          check: ['仅显示打开卡包券'],
        }}
      >
        <div className={styles['query-body']}>
          <div style={{ display: 'flex' }}>
            <Form.Item label="活动定义" name="activityId" style={{ width: 260 }}>
              <Input />
            </Form.Item>
            <Form.Item label="活动名称" name="activity" style={{ width: 260 }}>
              <Input />
            </Form.Item>
            <Form.Item
              labelCol={{ span: 9 }}
              label="活动有效期"
              name="timeRange"
              style={{ width: 380 }}
            >
              <DatePicker.RangePicker />
            </Form.Item>
          </div>
          <div
            style={{
              display: 'flex',
            }}
          >
            <Button style={{ marginLeft: 20 }} onClick={resetForm}>
              重置
            </Button>
            <Button style={{ marginLeft: 20 }} type="primary" onClick={handleQuey}>
              查询
            </Button>
          </div>
        </div>
        <div className={styles['query-body']}>
          <div style={{ display: 'flex' }}>
            <Form.Item label="渠道" name="channel" style={{ width: 260 }}>
              <Select
                options={[
                  { label: '堂食', value: 'CPOS' },
                  { label: '外送', value: 'Delivery' },
                ]}
              />
            </Form.Item>
            <Form.Item label="Campaign Code" name="campaignCode" style={{ width: 260 }}>
              <Input />
            </Form.Item>
          </div>
          <Form.Item label={null} name="check">
            <Checkbox.Group
              options={[
                {
                  value: '仅显示打开卡包券',
                  label: '仅显示打开卡包券',
                },
              ]}
            />
          </Form.Item>
        </div>
      </Form>

      <div style={{ marginTop: 30 }}>
        <Table
          // key="activityId"
          // @ts-ignore
          columns={columns}
          rowKey="activityId"
          rowSelection={rowSelection}
          dataSource={tableData}
          onChange={onChangePagination}
          pagination={{
            current: pageNo,
            pageSize,
            total,
            showSizeChanger: true,
            showTotal: (totals: any) => `共 ${totals} 条`,
          }}
          scroll={{ x: 1500 }}
          // expandable={{
          //   expandedRowRender: (record: { activityId: any }) =>
          //     record.activityId === expandId && (
          //       <RenderExpandedRow
          //         detail={detailItem}
          //         channel={channelWatch}
          //         queryForm={queryForm}
          //       />
          //     ),
          //   expandedRowKeys: [expandId],
          // }}
          loading={loading}
        />
      </div>

      <div className={styles['btns-body']}>
        <Button
          style={{ marginRight: 16 }}
          onClick={() => {
            back();
          }}
        >
          返回
        </Button>
        <Button
          style={{ marginRight: 16 }}
          type="primary"
          onClick={() => {
            handleSure();
          }}
          loading={btnLoading}
        >
          确定
        </Button>
      </div>
    </div>
  );
};

export default ChooseActivty;
